<?php

namespace App\Repositories;

use App\User;

/**
 * 用户仓库
 */
class UserRepository
{
    /**
     * 获取数据
     * @return array
     */
    public function getPageList()
    {
        $search_text = request('search', '');

        $user = new User;

        /*名称或者邮箱搜索*/
        if ($search_text) {
            $user = $user->where('name', 'like', "%".$search_text."%")->orWhere('email', 'like', "%".$search_text."%");
        }

        return $user->paginate(config("global.paginate"));
    }


    /**
     * 添加用户
     * @param $request
     * @return bool
     */
    public function store($request)
    {
        $user = new User;

        $userData = $request->all();
        //密码进行加密
        $userData['password'] = bcrypt($userData['password']);

        if ($user->fill($userData)->save()) {
            flash(trans('alerts.users.created_success'))->success();
            return true;
        }
        flash(trans('alerts.users.created_error'))->error();
        return false;
    }

    /**
     * 修改用户视图
     * @param $id
     * @return array
     */
    public function edit($id)
    {
        $user = User::find($id);
        if ($user) {
            return $user;
        }
        abort(404);
    }

    /**
     * 修改用户资料
     * @param $request
     * @param $id
     * @return bool
     */
    public function update($request, $id)
    {
        $user = User::find($id);
        if ($user) {
            $request = $request->all();
            $request['password'] != $user->password && $request['password'] = bcrypt($request['password']);
            if ($user->fill($request)->save()) {
                flash(trans('alerts.users.updated_success'))->success();
                return true;
            }
            flash(trans('alerts.users.updated_error'))->error();
            return false;
        }
        abort(404);
    }

    /**
     * 删除角色
     * @param $id
     * @return bool
     */
    public function destroy($id)
    {
        $isDelete = User::destroy($id);
        if ($isDelete) {
            flash(trans('alerts.users.deleted_success'))->success();
            return true;
        }
        flash(trans('alerts.users.deleted_error'))->error();
        return false;
    }
}